const express = require('express');
const bodyParser = require("body-parser");
const fs = require('fs');
const app = express();
class Success {
  constructor(data, msg) {
    return {
      code: 1,
      data: data,
      msg: msg,
      success: true,
    }
  }
}
class Error {
  constructor(data, msg) {
    return {
      code: 0,
      data: data,
      msg: msg,
      success: false,
    }
  }
}
const serverPort = 3000
/*
注意：
1. 需要将允许跨域的请求代码放在所有的路由前面，因为请求被express接受到的时候，拦截的顺序是根据自己写的代码路由顺序决定的，一旦满足拦截条件，如果不执行next()方法，则就不会继续把请求发送给下一个路由拦截器。
2. `  res.header("Access-Control-Allow-Origin", req.headers.origin);`不能使用 *， 否则协议不通过
*/
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.all('*', (req, res, next) => {
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  res.header("Access-Control-Allow-Origin", '*');
  res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("Access-Control-Allow-Credentials", "true");
  res.header("X-Powered-By", ' 3.2.1')
  if (req.method === "OPTIONS") res.send(200); /*让options请求快速返回*/
  else next();
});
app.get('/getList', async (req, res) => {
  try {
    const dataLsit = await getJsonData()
    res.send(sendData({ type: 'success', data: dataLsit }))
  } catch (error) {
    res.send(sendData({ type: 'error', msg: error.message }))
  }
});
app.post('/add', async (req, res) => {
  try {
    const data = req.body
    if (JSON.stringify(data) === '{}') {
      res.send(sendData({ type: 'error', msg: '参数错误' }))
      return
    }
    const dataLsit = await getJsonData() || []
    const lastIndex = dataLsit.length - 1
    dataLsit.push({
      ...data,
      _id: lastIndex + 1
    })
    const str = JSON.stringify(dataLsit)
    await setJsonData(str)
    res.send(sendData({ type: 'success' }))
  } catch (err) {
    res.send(sendData({ type: 'error', msg: err.message }))
  }
});
app.post('/remove', async (req, res) => {
  try {
    const data = req.body
    if (JSON.stringify(data) === '{}' || data._id === '') {
      res.send(sendData({ type: 'error', msg: '参数错误' }))
      return
    }
    const dataLsit = await getJsonData()
    const newDataLsit = dataLsit.filter(item => item._id !== data._id)
    const str = JSON.stringify(newDataLsit)
    await setJsonData(str)
    res.send(sendData({ type: 'success' }))
  } catch (error) {
    res.send(sendData({ type: 'error', msg: error.message }))
  }
})
app.get('/removeAll', async (req, res) => {
  try {
    await setJsonData([])
    res.send(sendData({ type: 'success' }))
  } catch (error) {
    res.send(sendData({ type: 'error', msg: error.message }))
  }
})
function sendData ({ type, data = {}, msg = '' }) {
  switch (type) {
    case 'success':
      return new Success(data, msg)
    case 'error':
      return new Error(data, msg)
  }
}
function setJsonData (str) {
  return new Promise((resolve, reject) => {
    try {
      fs.writeFile('./mock/data.json', str, (err) => {
        if (err) {
          resolve(err)
        }
        resolve()
      })
    } catch (error) {
      resolve(error)
    }
  })
}
function getJsonData () {
  return new Promise((resolve, reject) => {
    try {
      fs.readFile('./mock/data.json', function (err, data) {
        if (err) {
          resolve(err)
        }
        try {
          const person = data.toString();
          if (person) {
            const result = JSON.parse(person)
            return resolve(result)
          }
          resolve([])
        } catch (error) {
          reject(error)
        }
      })
    } catch (error) {
      reject(error)
    }
  })
}
app.listen(serverPort, () => {
  console.log(`后台服务端口启动在`);
  console.log(`http://localhost:${serverPort}`);
});